package mq;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
@Component
@Slf4j
public class BiConsumer {
    /**
     * 接收消息:指定程序监听的消息队列和确认机制
     * @param message
     */
    @Resource
    private ChartService chartService;
    @RabbitListener(queues = {"bi_queue"},ackMode = "MANUAL", autoStartup = "true")
    public void onMessage(String  id, Channel  channel,@Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        String url = "https://spark-api-open.xf-yun.com/v2/chat/completions";
        Chart chart = chartService.getById(id);

        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("2");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            updateChart.setStatus("0");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图表更新失败");
        }

        //调用ai
        String response = HttpRequest
                .post(url)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer XPjicojybmBHObDjWRsm:qngUsuaHjsMZIMtsRXfx")
                .body(chart.getAiMessage())
                .execute().body();

        // 解析 JSON 响应
        JSONObject jsonResponse = JSONUtil.parseObj(response);
        // 获取 choices 数组
        JSONArray choices = jsonResponse.getJSONArray("choices");
        if (choices == null || choices.isEmpty()) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI响应格式异常");
        }
        // 提取第一个 choice 中的 message.content
        JSONObject firstChoice = choices.getJSONObject(0);
        JSONObject AImessage = firstChoice.getJSONObject("message");
        String content = AImessage.getStr("content");
        //用【【【【【分割内容
        String[] split = content.split("【【【【【");
        //获取数组的第一个元素
        String code = split[1];
        String aiResult = split[2];

        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setStatus("3");
        updateChartResult.setGenChart(code);
        updateChartResult.setGenResult(aiResult);

        boolean c = chartService.updateById(updateChartResult);
        if (!c) {
            updateChartResult.setStatus("0");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图表更新失败");
        }
    log.info("接收到消息：{}", chart.getAiMessage());
    channel.basicAck(deliveryTag, false);
    }
}
